import copy
import random


def decode(starting):
    max_attempts = 1000  # 添加最大尝试次数
    attempt = 0
    
    while attempt < max_attempts:
        attempt += 1
        starting_list = copy.deepcopy(starting)
        complete_list = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
        step_list = []

        while len(step_list) < 6:  # 限制最大步数为6
            num1 = random.randint(0, 2)
            num2 = random.randint(0, 2)
            num_list = [num1, num2]
            step_list.append(num_list)

            conversion(starting_list, num1, num2)

            if starting_list == complete_list:
                print('解决方案：')
                print('依次点击: ', end="")
                for i, item in enumerate(step_list):
                    position = item[0]*3 + item[1] + 1
                    print(f'{position}', end="" if i == len(step_list)-1 else " -> ")
                print("\n总步数：", len(step_list))
                return True
                
    print("未找到6步以内的解决方案，请重试")
    return False


# 计算规律
def conversion(starting_list, num1, num2):
    starting_list[num1][num2] = -starting_list[num1][num2]

    for item in range(4):
        a = num1
        b = num2
        if item == 0:
            a -= 1
        elif item == 1:
            a += 1
        elif item == 2:
            b -= 1
        else:
            b += 1

        if 0 <= a <= 2 and 0 <= b <= 2:
            starting_list[a][b] = -starting_list[a][b]


if __name__ == "__main__":
    '''
    修改 starting
    -1代表不亮  1代表亮
    若次数多，可再次运行代码
    '''
    starting = [
        [-1, 1, 1],
        [-1, 1, -1],
        [1, 1, 1]
    ]
    decode(starting)
